<template>
  <div class="legal-knowledge-questionnaire">
    <div class="questionnaire-header">
      <h3 class="section-title">法律知识问卷</h3>
      <p class="section-description">本问卷包含20道选择题和30道判断题，每道题2分，总分100分。</p>
    </div>

    <div class="questionnaire-form">
      <form @submit.prevent="submitQuestionnaire">
        <!-- 基本信息 -->
        <div class="form-section">
          <h4 class="form-section-title">基本信息</h4>
          <div class="form-group">
            <label for="name">姓名：</label>
            <input
              type="text"
              id="name"
              v-model="formData.name"
              required
              class="form-input"
              placeholder="请输入您的姓名"
            />
          </div>
          <div class="form-group">
            <label for="class">班级：</label>
            <input
              type="text"
              id="class"
              v-model="formData.class"
              required
              class="form-input"
              placeholder="请输入您的班级"
            />
          </div>
        </div>

        <!-- 选择题部分 -->
        <div class="form-section">
          <h4 class="form-section-title">选择题（每题2分，共20题）</h4>
          <div
            v-for="(question, index) in questions.multipleChoice"
            :key="`mc-${index}`"
            class="question-item"
          >
            <div class="question-text">
              <span class="question-number">{{ question.id }}.</span>
              {{ question.text }}
            </div>
            <div class="options-container">
              <div
                v-for="option in question.options"
                :key="option.value"
                class="option-item"
              >
                <input
                  type="radio"
                  :id="`q${question.id}-${option.value}`"
                  :name="`q${question.id}`"
                  :value="option.value"
                  v-model="formData.answers[question.id]"
                />
                <label :for="`q${question.id}-${option.value}`">
                  {{ option.value }}. {{ option.text }}
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- 判断题部分 -->
        <div class="form-section">
          <h4 class="form-section-title">判断题（每题2分，共30题）</h4>
          <div
            v-for="(question, index) in questions.trueFalse"
            :key="`tf-${index}`"
            class="question-item"
          >
            <div class="question-text">
              <span class="question-number">{{ question.id }}.</span>
              {{ question.text }}
            </div>
            <div class="options-container">
              <div class="option-item">
                <input
                  type="radio"
                  :id="`q${question.id}-true`"
                  :name="`q${question.id}`"
                  value="正确"
                  v-model="formData.answers[question.id]"
                />
                <label :for="`q${question.id}-true`">正确</label>
              </div>
              <div class="option-item">
                <input
                  type="radio"
                  :id="`q${question.id}-false`"
                  :name="`q${question.id}`"
                  value="错误"
                  v-model="formData.answers[question.id]"
                />
                <label :for="`q${question.id}-false`">错误</label>
              </div>
            </div>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <button type="submit" class="submit-button" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : '提交问卷' }}
          </button>
        </div>
      </form>
    </div>

    <!-- 结果弹窗 -->
    <div class="result-modal" v-if="showResult">
      <div class="result-content">
        <h3 class="result-title">问卷评分结果</h3>
        <div class="result-summary">
          <div class="result-item">
            <span class="result-label">选择题得分：</span>
            <span class="result-value">{{ result.multipleChoiceScore }} / 40</span>
          </div>
          <div class="result-item">
            <span class="result-label">判断题得分：</span>
            <span class="result-value">{{ result.trueFalseScore }} / 60</span>
          </div>
          <div class="result-item total-score">
            <span class="result-label">总分：</span>
            <span class="result-value">{{ result.totalScore }} / 100</span>
          </div>
          <div class="result-item">
            <span class="result-label">等级：</span>
            <span class="result-value" :class="'grade-' + result.grade.toLowerCase()">
              {{ result.grade }}
            </span>
          </div>
        </div>

        <div class="wrong-answers" v-if="result.wrongQuestions.length > 0">
          <h4>错误题目：</h4>
          <ul class="wrong-list">
            <li v-for="(question, index) in result.wrongQuestions" :key="index">
              第{{ question }}题
            </li>
          </ul>
        </div>

        <div class="result-actions">
          <button @click="closeResult" class="close-button">关闭</button>
          <button @click="resetForm" class="reset-button">重新作答</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LegalKnowledgeQuestionnaire',
  data() {
    return {
      isLoading: true,
      isSubmitting: false,
      showResult: false,
      questions: {
        multipleChoice: [],
        trueFalse: []
      },
      formData: {
        name: '',
        class: '',
        answers: {}
      },
      result: {
        multipleChoiceScore: 0,
        trueFalseScore: 0,
        totalScore: 0,
        grade: '',
        wrongQuestions: []
      },
      answers: {} // 存储正确答案
    }
  },
  mounted() {
    this.loadQuestions();
  },
  methods: {
    async loadQuestions() {
      try {
        // 尝试从正确路径加载问卷
        let response = await fetch('/data/wenjuan/LawQuestion.txt');
        console.log('Loading questions from:', '/data/wenjuan/LawQuestion.txt');

        // 如果第一个路径失败，尝试备用路径
        if (!response.ok) {
          console.log('第一个路径失败，尝试备用路径');
          response = await fetch('/data/LawQuestion.txt');
          console.log('Loading questions from backup path:', '/data/LawQuestion.txt');
        }
        if (response.ok) {
          const text = await response.text();
          this.parseQuestions(text);
          this.isLoading = false;
        } else {
          console.error('加载问卷失败');
        }
      } catch (error) {
        console.error('加载问卷出错:', error);
      }
    },

    parseQuestions(text) {
      console.log('开始解析问卷文本');
      console.log('文本长度:', text.length);

      // 分割文本为选择题和判断题部分
      const parts = text.split('判断题');
      if (parts.length < 2) {
        console.error('问卷格式错误');
        return;
      }

      console.log('成功分割选择题和判断题部分');

      const multipleChoiceText = parts[0].trim();
      const trueFalseText = '判断题' + parts[1].trim();

      console.log('选择题文本长度:', multipleChoiceText.length);
      console.log('判断题文本长度:', trueFalseText.length);

      // 解析选择题
      this.parseMultipleChoiceQuestions(multipleChoiceText);

      // 解析判断题
      this.parseTrueFalseQuestions(trueFalseText);

      console.log('解析完成，选择题数量:', this.questions.multipleChoice.length);
      console.log('解析完成，判断题数量:', this.questions.trueFalse.length);
    },

    parseMultipleChoiceQuestions(text) {
      // 使用正则表达式匹配每道选择题
      const questionRegex = /(\d+)\.\s+(.*?)(?=\s+A\.|$)([\s\S]*?)(?=\d+\.|判断题|$)/g;

      // 使用更精确的正则表达式匹配选项
      // 匹配A选项
      const optionARegex = /\s+A\.\s+(.*?)(?=\s+B\.)/g;
      // 匹配B选项
      const optionBRegex = /\s+B\.\s+(.*?)(?=\s+C\.)/g;
      // 匹配C选项
      const optionCRegex = /\s+C\.\s+(.*?)(?=\s+D\.)/g;
      // 匹配D选项
      const optionDRegex = /\s+D\.\s+(.*?)(?=\s+答案：|$)/g;
      const answerRegex = /答案：([A-D])/;

      let match;
      while ((match = questionRegex.exec(text)) !== null) {
        const id = parseInt(match[1]);
        const questionText = match[2].trim();
        const optionsText = match[3];

        // 提取选项
        const options = [];

        // 匹配A选项
        let optionAMatch;
        while ((optionAMatch = optionARegex.exec(optionsText)) !== null) {
          options.push({
            value: 'A',
            text: optionAMatch[1].trim()
          });
        }

        // 匹配B选项
        let optionBMatch;
        while ((optionBMatch = optionBRegex.exec(optionsText)) !== null) {
          options.push({
            value: 'B',
            text: optionBMatch[1].trim()
          });
        }

        // 匹配C选项
        let optionCMatch;
        while ((optionCMatch = optionCRegex.exec(optionsText)) !== null) {
          options.push({
            value: 'C',
            text: optionCMatch[1].trim()
          });
        }

        // 匹配D选项
        let optionDMatch;
        while ((optionDMatch = optionDRegex.exec(optionsText)) !== null) {
          options.push({
            value: 'D',
            text: optionDMatch[1].trim()
          });
        }

        // 提取答案
        const answerMatch = answerRegex.exec(optionsText);
        if (answerMatch) {
          this.answers[id] = answerMatch[1];
        }

        // 检查选项是否完整
        console.log(`题目 ${id} 的选项数量:`, options.length);
        if (options.length < 4) {
          console.warn(`题目 ${id} 的选项不完整，只有 ${options.length} 个选项`);

          // 确保所有选项都存在
          const optionValues = options.map(opt => opt.value);
          if (!optionValues.includes('A')) {
            options.push({ value: 'A', text: '选项A' });
          }
          if (!optionValues.includes('B')) {
            options.push({ value: 'B', text: '选项B' });
          }
          if (!optionValues.includes('C')) {
            options.push({ value: 'C', text: '选项C' });
          }
          if (!optionValues.includes('D')) {
            options.push({ value: 'D', text: '选项D' });
          }

          // 按选项顺序排序
          options.sort((a, b) => a.value.localeCompare(b.value));
        }

        this.questions.multipleChoice.push({
          id,
          text: questionText,
          options
        });
      }
    },

    parseTrueFalseQuestions(text) {
      // 使用正则表达式匹配每道判断题
      const questionRegex = /(\d+)\.\s+(.*?)(?=\s+答案：|$)([\s\S]*?)(?=\d+\.|$)/g;
      const answerRegex = /答案：(正确|错误)/;

      let match;
      while ((match = questionRegex.exec(text)) !== null) {
        const id = parseInt(match[1]);
        const questionText = match[2].trim();
        const answerText = match[3];

        // 提取答案
        const answerMatch = answerRegex.exec(answerText);
        if (answerMatch) {
          this.answers[id] = answerMatch[1];
        }

        this.questions.trueFalse.push({
          id,
          text: questionText
        });
      }
    },

    async submitQuestionnaire() {
      if (this.isSubmitting) return;

      // 验证表单
      if (!this.formData.name || !this.formData.name.trim()) {
        alert('请输入您的姓名');
        return;
      }

      if (!this.formData.class || !this.formData.class.trim()) {
        alert('请输入您的班级');
        return;
      }

      // 检查是否所有题目都已回答
      const totalQuestions = this.questions.multipleChoice.length + this.questions.trueFalse.length;
      const answeredQuestions = Object.keys(this.formData.answers).length;

      if (answeredQuestions < totalQuestions) {
        const confirm = window.confirm(`您还有 ${totalQuestions - answeredQuestions} 道题目未作答，确定要提交吗？`);
        if (!confirm) return;
      }

      this.isSubmitting = true;

      try {
        // 评分
        this.gradeQuestionnaire();

        // 保存结果到CSV
        await this.saveResultToCSV();

        // 显示结果
        this.showResult = true;
      } catch (error) {
        console.error('提交问卷出错:', error);
        alert('提交问卷失败，请稍后重试');
      } finally {
        this.isSubmitting = false;
      }
    },

    gradeQuestionnaire() {
      let multipleChoiceCorrect = 0;
      let trueFalseCorrect = 0;
      const wrongQuestions = [];

      // 评分选择题
      this.questions.multipleChoice.forEach(question => {
        const userAnswer = this.formData.answers[question.id];
        const correctAnswer = this.answers[question.id];

        if (userAnswer === correctAnswer) {
          multipleChoiceCorrect++;
        } else if (userAnswer) {
          // 只记录已回答但错误的题目
          wrongQuestions.push(question.id);
        }
      });

      // 评分判断题
      this.questions.trueFalse.forEach(question => {
        const userAnswer = this.formData.answers[question.id];
        const correctAnswer = this.answers[question.id];

        if (userAnswer === correctAnswer) {
          trueFalseCorrect++;
        } else if (userAnswer) {
          // 只记录已回答但错误的题目
          wrongQuestions.push(question.id);
        }
      });

      // 计算分数
      const multipleChoiceScore = multipleChoiceCorrect * 2;
      const trueFalseScore = trueFalseCorrect * 2;
      const totalScore = multipleChoiceScore + trueFalseScore;

      // 确定等级
      let grade = '';
      if (totalScore >= 90) {
        grade = 'A';
      } else if (totalScore >= 80) {
        grade = 'B';
      } else if (totalScore >= 60) {
        grade = 'C';
      } else {
        grade = 'D';
      }

      // 更新结果
      this.result = {
        multipleChoiceScore,
        trueFalseScore,
        totalScore,
        grade,
        wrongQuestions: wrongQuestions.sort((a, b) => a - b)
      };
    },

    async saveResultToCSV() {
      try {
        // 准备CSV数据
        const csvData = {
          name: this.formData.name.trim(),
          class: this.formData.class.trim(),
          multipleChoiceScore: this.result.multipleChoiceScore,
          trueFalseScore: this.result.trueFalseScore,
          totalScore: this.result.totalScore,
          wrongQuestions: this.result.wrongQuestions.join('、'),
          grade: this.result.grade
        };

        // 发送数据到服务器
        const response = await fetch('/api/saveQuestionnaireResult', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(csvData)
        });

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.error || '保存失败');
        }

        const result = await response.json();
        console.log('问卷结果已保存:', result.message);
      } catch (error) {
        console.error('保存结果出错:', error);
        throw error;
      }
    },

    closeResult() {
      this.showResult = false;
    },

    resetForm() {
      this.formData = {
        name: '',
        class: '',
        answers: {}
      };
      this.showResult = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.legal-knowledge-questionnaire {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  color: #d3d6dd;

  .questionnaire-header {
    margin-bottom: 20px;

    .section-title {
      font-size: 18px;
      color: #68d8fe;
      margin-bottom: 10px;
    }

    .section-description {
      font-size: 14px;
      color: #a0a3aa;
      line-height: 1.5;
    }
  }

  .questionnaire-form {
    background-color: rgba(19, 25, 47, 0.7);
    border-radius: 5px;
    padding: 20px;
    border: 1px solid rgba(104, 216, 254, 0.3);

    .form-section {
      margin-bottom: 25px;

      .form-section-title {
        font-size: 16px;
        color: #68d8fe;
        margin-bottom: 15px;
        padding-bottom: 8px;
        border-bottom: 1px solid rgba(104, 216, 254, 0.3);
      }
    }

    .form-group {
      margin-bottom: 15px;
      display: flex;
      align-items: center;

      label {
        width: 80px;
        color: #d3d6dd;
        font-size: 14px;
      }

      .form-input {
        flex: 1;
        background-color: rgba(19, 25, 47, 0.8);
        border: 1px solid rgba(104, 216, 254, 0.4);
        border-radius: 4px;
        color: #d3d6dd;
        padding: 8px 12px;
        font-size: 14px;
        outline: none;

        &:focus {
          border-color: rgba(104, 216, 254, 0.8);
          box-shadow: 0 0 5px rgba(104, 216, 254, 0.3);
        }
      }
    }

    .question-item {
      margin-bottom: 20px;
      background-color: rgba(19, 25, 47, 0.5);
      border-radius: 4px;
      padding: 15px;
      border: 1px solid rgba(104, 216, 254, 0.2);

      .question-text {
        margin-bottom: 10px;
        font-size: 14px;
        line-height: 1.5;

        .question-number {
          font-weight: bold;
          color: #68d8fe;
          margin-right: 5px;
        }
      }

      .options-container {
        display: flex;
        flex-direction: column;
        gap: 10px;
        padding-left: 20px;

        .option-item {
          display: flex;
          align-items: center;

          input[type="radio"] {
            margin-right: 10px;
            cursor: pointer;
          }

          label {
            font-size: 14px;
            cursor: pointer;

            &:hover {
              color: #68d8fe;
            }
          }
        }
      }
    }

    .form-actions {
      display: flex;
      justify-content: center;
      margin-top: 30px;

      .submit-button {
        background-color: rgba(104, 216, 254, 0.2);
        border: 1px solid rgba(104, 216, 254, 0.5);
        color: #68d8fe;
        padding: 10px 30px;
        font-size: 16px;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background-color: rgba(104, 216, 254, 0.3);
          border-color: rgba(104, 216, 254, 0.7);
        }

        &:disabled {
          opacity: 0.6;
          cursor: not-allowed;
        }
      }
    }
  }

  .result-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;

    .result-content {
      background-color: rgba(19, 25, 47, 0.95);
      border-radius: 8px;
      padding: 25px;
      width: 500px;
      max-width: 90%;
      border: 2px solid rgba(104, 216, 254, 0.5);
      box-shadow: 0 0 20px rgba(104, 216, 254, 0.3);

      .result-title {
        font-size: 20px;
        color: #68d8fe;
        text-align: center;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 1px solid rgba(104, 216, 254, 0.3);
      }

      .result-summary {
        margin-bottom: 20px;

        .result-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          font-size: 16px;

          &.total-score {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px dashed rgba(104, 216, 254, 0.3);
            font-weight: bold;

            .result-value {
              font-size: 20px;
            }
          }

          .result-label {
            color: #d3d6dd;
          }

          .result-value {
            color: #68d8fe;

            &.grade-a {
              color: #67C23A;
            }

            &.grade-b {
              color: #409EFF;
            }

            &.grade-c {
              color: #E6A23C;
            }

            &.grade-d {
              color: #F56C6C;
            }
          }
        }
      }

      .wrong-answers {
        margin-bottom: 20px;

        h4 {
          font-size: 16px;
          color: #F56C6C;
          margin-bottom: 10px;
        }

        .wrong-list {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          padding-left: 20px;

          li {
            background-color: rgba(245, 108, 108, 0.1);
            border: 1px solid rgba(245, 108, 108, 0.3);
            color: #F56C6C;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 14px;
          }
        }
      }

      .result-actions {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin-top: 20px;

        button {
          padding: 8px 20px;
          border-radius: 4px;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.3s;

          &.close-button {
            background-color: rgba(104, 216, 254, 0.2);
            border: 1px solid rgba(104, 216, 254, 0.5);
            color: #68d8fe;

            &:hover {
              background-color: rgba(104, 216, 254, 0.3);
              border-color: rgba(104, 216, 254, 0.7);
            }
          }

          &.reset-button {
            background-color: rgba(245, 108, 108, 0.2);
            border: 1px solid rgba(245, 108, 108, 0.5);
            color: #F56C6C;

            &:hover {
              background-color: rgba(245, 108, 108, 0.3);
              border-color: rgba(245, 108, 108, 0.7);
            }
          }
        }
      }
    }
  }
}
</style>
